import axios from "axios";
import store from "../store/index";
import { getToken, setToken } from "@/utils/auth";

const service = axios.create({
  timeout: 10000,
  transformRequest: [
    data => {
      // 对 data 进行任意转换处理
      let ret = "";
      for (let it in data) {
        ret +=
          encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
      }
      ret = ret.substr(0, ret.length - 1);
      return ret;
    }
  ]
});

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["token"] = getToken();
    }
    // 页面跳转防止拦截上个页面的请求
    config.cancelToken = new axios.CancelToken(cancel => {
      window.__axiosCancelArr.push({ cancel });
    });
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (response.config.responseType == "blob") {
      return Promise.resolve(res);
    }
    if (res.code == 0) {
      setToken(response.headers.token);
      store.commit("SET_TOKEN", response.headers.token);
      return Promise.resolve(res);
    } else if (res.code == "INVALID" || res.code == "EXPIRED") {
      alert(res.message);
      store.dispatch("FedLogOut").then(() => {
        location.reload();
      });
    } else {
      alert(res.message);
      return Promise.reject(res);
    }
  },
  error => {
    if (
      error.code == "ECONNABORTED" &&
      error.message.indexOf("timeout") != -1
    ) {
      alert("请求接口超时！");
      return;
    }
    if (error.response) {
      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      if (error.response.status >= 500 && error.response.status < 600) {
        alert(`网络状态码${error.response.status}:服务端出错!`);
      } else {
        alert(error.message);
      }
    } else {
      if (error.message != "axiosCancel") {
        alert("网络出错！");
      }
    }
    return Promise.reject(error);
  }
);

export default service;
